package com.shd.edanpei.ui.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.shd.edanpei.R;
import com.shd.edanpei.base.BaseActivity;
import com.shd.edanpei.base.BasePresenterImpl;
import com.shd.edanpei.base.MyApplication;
import com.shd.edanpei.base.network.api.ApiCreator;
import com.shd.edanpei.base.network.exception.ResponeThrowable;
import com.shd.edanpei.base.network.rx.BaseObserver;
import com.shd.edanpei.base.network.rx.RxTransformer;
import com.shd.edanpei.bean.VersionBean;
import com.shd.edanpei.db.DaoManager;
import com.shd.edanpei.enums.UrlEnum;
import com.shd.edanpei.util.AcCollector;
import com.shd.edanpei.util.DataCleanManager;
import com.shd.edanpei.util.ToastUtil;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by mc on 2018/3/29.
 * 设置
 */
public class SettingsActivity extends BaseActivity {

    @BindView(R.id.headline)
    TextView headline;
    @BindView(R.id.tv_cacheSize)
    TextView tvCacheSize;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.ll_version)
    LinearLayout llCheckVersion;

    @Override
    protected int setLayout() {
        return R.layout.activity_setting;
    }

    @Override
    protected BasePresenterImpl bindPresenter() {
        return null;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        headline.setText("设置");
        getCacheSize();
        getMyVersion();
//        Var var1="1";
    }

    private void getMyVersion() {
        try {
            PackageInfo packageInfo = this.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(this.getPackageName(), 0);
            tvVersion.setText(packageInfo.versionName);//热修复可以加一个小括号再加版本
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void getCacheSize() {
        try {
            String cacheSize = DataCleanManager.getCacheSize(MyApplication.getApplication().getExternalCacheDir());
            tvCacheSize.setText(cacheSize);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @OnClick(R.id.ll_version)
    void checkVersion(){
        ApiCreator.getApi().appVersion("android")
                .compose(RxTransformer.<VersionBean>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<VersionBean>() {
                    @Override
                    protected void onSuccess(VersionBean data) {
//                        data.setAndroidIsUpdate(false);
                        try {
                            PackageInfo packageInfo = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
                            int versionCode = packageInfo.versionCode;
                            if (versionCode < data.getVersionNo()) {
                                if (data.isAndroidIsUpdate()) {
                                    //需强制更新
                                    toForcedUpadating();
                                } else {
                                    //非强制更新
                                   toUpdate();
                                }
                            } else {
                                ToastUtil.showToast("该版本已是最新版本，无需更新！");

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(ResponeThrowable throwable) {
                       // toSplashActivity();
                    }
                });
    }
    @Override
    protected void initListener() {

    }

    @OnClick(R.id.iv_headline_back)
    void close() {
        finish();
    }

    @OnClick(R.id.tv_about)
    void clickAbout() {
        WebActivity.start(this, "关于我们", null, UrlEnum.h.getType());
    }


    @OnClick(R.id.ll_cacheSize)
    void onClean() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("当前缓存：" + tvCacheSize.getText().toString())
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("清除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showLoading("清除中...");
                        DataCleanManager.cleanCustomCache(ChoosePicActivity.SCARD_PIC_PATH);
                        getCacheSize();
                        stopLoading();
                    }
                })
                .show();

    }

    @OnClick(R.id.tv_logout)
    void logout() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("是否退出当前账号?")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DaoManager.getInstance().logout();
                        AcCollector.finishOther(getContext());
                        startActivity(LoginActivity.class);
                        finish();
                    }
                })
                .show();

    }

    private void toForcedUpadating() {
        AlertDialog builder = new AlertDialog.Builder(this)
                .setTitle("发现新版本")
                .setCancelable(false)
                .setPositiveButton("去更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toMarket(SettingsActivity.this, "com.shd.edanpei", null);
                    }
                }).show();
    }
    /**
     * 跳转应用商店.
     *
     * @param context   {@link Context}
     * @param appPkg    包名
     * @param marketPkg 应用商店包名
     * @return {@code true} 跳转成功 <br> {@code false} 跳转失败
     */
    public static boolean toMarket(Context context, String appPkg, String marketPkg) {
        Uri uri = Uri.parse("market://details?id=" + appPkg);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (marketPkg != null) {// 如果没给市场的包名，则系统会弹出市场的列表让你进行选择。
            intent.setPackage(marketPkg);
        }
        try {
            context.startActivity(intent);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
    private void toUpdate() {
        AlertDialog builder = new AlertDialog.Builder(this)
                .setTitle("发现新版本")
                .setCancelable(false)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //toSplashActivity();
                    }
                })
                .setPositiveButton("去更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toMarket(SettingsActivity.this, "com.shd.edanpei", null);
                    }
                }).show();
    }
}
